import { onCleanup, onMount } from "solid-js";
import { createStore } from "solid-js/store";

type Options = {
  key1: string;
  key2: string;
  onAllPress: () => void;
};

type State = {
  key1: number;
  key2: number;
};

export default function useKeysPress({ key1, key2, onAllPress }: Options) {
  if (key1 === key2) {
    throw new Error("Key1 and key2 should be different.");
  }

  const [__, setState] = createStore<State>({ key1: 0, key2: 0 });

  const checkEvent = (state: State) => {
    if (state.key1 === 1 && state.key2 === 1) {
      onAllPress();
    }
  };

  const handleKeyDown = (e: KeyboardEvent) => {
    switch (e.key) {
      case key1:
        setState((state) => {
          const newState = { ...state, key1: state.key1 + 1 };
          checkEvent(newState);
          return newState;
        });
        break;
      case key2:
        setState((state) => {
          const newState = { ...state, key2: state.key2 + 1 };
          checkEvent(newState);
          return newState;
        });
        break;
    }
  };

  const handleKeyUp = (e: KeyboardEvent) => {
    switch (e.key) {
      case key1:
        setState("key1", () => 0);
        break;
      case key2:
        setState("key2", () => 0);
        break;
    }
  };

  onMount(() => {
    const abort = new AbortController();

    const opts = () => ({ signal: abort.signal });
    window.addEventListener("keydown", handleKeyDown, opts());
    window.addEventListener("keyup", handleKeyUp, opts());

    onCleanup(() => {
      abort.abort();
    });
  });

  return { key1, key2 };
}
